package com.zhentao.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.Brand;
import com.zhentao.pojo.Category;
import com.zhentao.pojo.CategoryBrandRelation;
import com.zhentao.pojo.Product;
import com.zhentao.service.BrandService;
import com.zhentao.service.CategoryBrandRelationService;
import com.zhentao.service.CategoryService;
import com.zhentao.service.ProductService;
import com.zhentao.util.BusinessException;
import com.zhentao.util.MinioUtil;
import com.zhentao.util.Result;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private MinioUtil minioUtil;

    // 管理端一系列增删改查
    @RequestMapping("findCategory")
    public Result findCategory() {
        List<Category> list = categoryService.list();
        return Result.OK(list);
    }

    // 根据分类级别存储到不同桶的接口
    @PostMapping(value = "/addCategory1", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result addCategory1(
            @RequestPart("category") String categoryJson,
            @RequestPart(value = "icon", required = false) MultipartFile iconFile) {
        try {
            // 用 fastjson2 将 JSON 字符串转为 Category 对象
            Category category = JSON.parseObject(categoryJson, Category.class);
            // 处理图片上传
            if (iconFile != null && !iconFile.isEmpty()) {
                String imagePath = minioUtil.upload(iconFile);
                category.setIcon(imagePath);
            }
            // 设置一级分类的相关属性
            category.setParentId(0L); // 一级分类的父 ID 通常设为 0
            category.setLevel(1);
            category.setStatus(1);
            category.setCreateTime(new Date());
            category.setUpdateTime(new Date());
            category.setIsDeleted(0);
            // 计算 sort 值，这里简单假设一级分类的起始 sort 值为 100
            Integer maxSort = categoryService.getMaxSortByParentId(0L);
            category.setSort(maxSort != null ? maxSort + 10 : 100);
            // 保存分类信息到数据库
            categoryService.save(category);
            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR("添加一级分类失败: " + e.getMessage());
        }
    }

    // 添加二级分类
    @PostMapping("addCategory2")
    public Result addCategory2(
            @RequestParam Long id,
            @RequestPart("category") Category category,
            @RequestPart(value = "icon", required = false) MultipartFile iconFile) {

        try {
            // 校验父分类
            Category parent = categoryService.getById(id);
            if (parent == null || parent.getIsDeleted() == 1) {
                return Result.ERROR("父分类不存在或已被删除");
            }

            // 处理图片上传
            if (iconFile != null && !iconFile.isEmpty()) {
                String imagePath = minioUtil.upload(iconFile);
                category.setIcon(imagePath);
            }

            // 计算sort值
            Integer childCount = categoryService.getChildCount(id);
            category.setSort(parent.getSort() + childCount * 10 + 10);

            // 设置其他属性
            category.setParentId(id);
            category.setLevel(2);
            category.setStatus(1);
            category.setCreateTime(new Date());
            category.setUpdateTime(new Date());
            category.setIsDeleted(0);

            categoryService.save(category);
            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR("添加分类失败: " + e.getMessage());
        }
    }

    // 添加三级分类
    @PostMapping("addCategory3")
    public Result addCategory3(
            @RequestParam Long parentId,
            @RequestPart("category") Category category,
            @RequestPart(value = "icon", required = false) MultipartFile iconFile) {

        try {
            // 校验父分类
            Category parent = categoryService.getById(parentId);
            if (parent == null || parent.getIsDeleted() == 1 || parent.getLevel() != 2) {
                return Result.ERROR("父分类不存在或不是二级分类");
            }

            // 处理图片上传
            if (iconFile != null && !iconFile.isEmpty()) {
                String imagePath = minioUtil.upload(iconFile);
                category.setIcon(imagePath);
            }

            // 计算sort值
            Integer childCount = categoryService.getChildCount(parentId);
            category.setSort(parent.getSort() + childCount + 1);

            // 设置其他属性
            category.setParentId(parentId);
            category.setLevel(3);
            category.setStatus(1);
            category.setCreateTime(new Date());
            category.setUpdateTime(new Date());
            category.setIsDeleted(0);

            categoryService.save(category);
            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR("添加分类失败: " + e.getMessage());
        }
    }


    // 从 Excel 文件导入分类信息
    @PostMapping("/importCategories")
    public Result importCategories(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook(inputStream);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 存储分类信息的列表
            List<Category> categories = new ArrayList<>();

            // 从第二行开始读取数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                Category category = new Category();
                category.setId((long) row.getCell(0).getNumericCellValue());
                category.setName(row.getCell(1).getStringCellValue());
                category.setDescription(row.getCell(2).getStringCellValue());
                category.setIcon(row.getCell(3).getStringCellValue());
                category.setLevel((int) row.getCell(4).getNumericCellValue());
                category.setStatus((int) row.getCell(5).getNumericCellValue());
                category.setSort((int) row.getCell(6).getNumericCellValue());
                category.setParentId((long) row.getCell(7).getNumericCellValue());
                categories.add(category);
            }

            // 保存分类信息到数据库
            categoryService.saveBatch(categories);

            return Result.OK();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.ERROR("导入失败: " + e.getMessage());
        }
    }
    // 导出分类信息到 Excel
    @GetMapping("/exportCategories")
    public ResponseEntity<byte[]> exportCategories() {
        // 获取所有分类信息
        List<Category> categories = categoryService.list();

        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Categories");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "Name", "Description", "Icon", "Level", "Status", "Sort", "Parent ID"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        for (int i = 0; i < categories.size(); i++) {
            Category category = categories.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(category.getId());
            row.createCell(1).setCellValue(category.getName());
            row.createCell(2).setCellValue(category.getDescription());
            row.createCell(3).setCellValue(category.getIcon());
            row.createCell(4).setCellValue(category.getLevel());
            row.createCell(5).setCellValue(category.getStatus());
            row.createCell(6).setCellValue(category.getSort());
            row.createCell(7).setCellValue(category.getParentId());
        }

        // 调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置响应头
        HttpHeaders headers1 = new HttpHeaders();
        headers1.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers1.setContentDispositionFormData("attachment", "categories.xlsx");

        return new ResponseEntity<>(outputStream.toByteArray(), headers1, HttpStatus.OK);
    }
    // 计算sort值
    private int calculateSortValue(Category parent, Integer childCount, int level) {
        if (level == 2) {
            return parent.getSort() + childCount * 10 + 10;
        } else {
            return parent.getSort() + childCount + 1;
        }
    }

    // 其他原有方法保持不变
    @RequestMapping("delCategory")
    public Result delCategory(Long id) {
        Category category = categoryService.getById(id);
        if (category == null || category.getIsDeleted() == 1) {
            return Result.ERROR("分类不存在或已被删除");
        }

        // 1. 检查是否有子分类
        int childCount = categoryService.getChildCount(id);
        if (childCount > 0) {
            return Result.ERROR("请先删除所有子分类");
        }

        // 2. 检查是否有品牌关联
        QueryWrapper<CategoryBrandRelation> relationQuery = new QueryWrapper<>();
        relationQuery.eq("category_id", id);
        long relationCount = categoryBrandRelationService.count(relationQuery);
        if (relationCount > 0) {
            return Result.ERROR("请先解除品牌关联");
        }

        // 3. 执行逻辑删除
        category.setIsDeleted(1);
        category.setUpdateTime(new Date());
        categoryService.updateById(category);
        return Result.OK();
    }

    @PostMapping(value = "/updateCategory", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result updateCategory(
            @RequestPart("category") String categoryJson,
            @RequestPart(value = "icon", required = false) MultipartFile iconFile) {
        try {
            // 1. 解析分类数据
            Category category = JSON.parseObject(categoryJson, Category.class);

            // 2. 参数校验
            if (category.getId() == null) {
                return Result.ERROR("分类ID不能为空");
            }

            // 3. 检查分类是否存在
            Category existing = categoryService.getById(category.getId());
            if (existing == null || existing.getIsDeleted() == 1) {
                return Result.ERROR("分类不存在或已被删除");
            }

            // 4. 处理图片上传
            if (iconFile != null && !iconFile.isEmpty()) {
                String imagePath = minioUtil.upload(iconFile);
                category.setIcon(imagePath);
            } else {
                // 保持原有图片
                category.setIcon(existing.getIcon());
            }

            // 5. 设置可更新字段（包括状态）
            Category update = new Category();
            update.setId(category.getId());
            update.setName(category.getName());
            update.setDescription(category.getDescription());
            update.setIcon(category.getIcon());
            update.setStatus(category.getStatus());  // 确保状态字段被更新
            update.setUpdateTime(new Date());

            // 6. 执行更新
            categoryService.updateById(update);
            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR("更新分类失败: " + e.getMessage());
        }
    }

    /**
     * 修改分类排序位置
     * @param categoryId 要移动的分类ID
     * @param newParentId 新父分类ID（可选，不传表示不修改父级）
     * @param position 位置（before/after/append，默认为append）
     * @param relativeId 参考分类ID（position为before/after时必填）
     * @return 操作结果
     */
    @RequestMapping("updateCategoryPosition")
    public Result updateCategoryPosition(
            @RequestParam Long categoryId,
            @RequestParam(required = false) Long newParentId,
            @RequestParam(defaultValue = "append") String position,
            @RequestParam(required = false) Long relativeId) {

        try {
            // 1. 校验分类是否存在
            Category category = categoryService.getById(categoryId);
            if (category == null || category.getIsDeleted() == 1) {
                return Result.ERROR("分类不存在");
            }

            // 2. 如果修改父分类，检查是否合法
            if (newParentId != null && !newParentId.equals(category.getParentId())) {
                // 检查是否移动到自己的子分类下
                if (isDescendant(newParentId, categoryId)) {
                    return Result.ERROR("不能将分类移动到自己的子分类下");
                }

                // 检查新父分类是否存在
                Category newParent = categoryService.getById(newParentId);
                if (newParent == null || newParent.getIsDeleted() == 1) {
                    return Result.ERROR("新父分类不存在");
                }
            } else {
                newParentId = category.getParentId(); // 不修改父分类
            }

            // 3. 计算新sort值
            Integer newSort = calculateSortValue(newParentId, position, relativeId);

            // 4. 更新分类
            Category update = new Category();
            update.setId(categoryId);
            if (newParentId != null && !newParentId.equals(category.getParentId())) {
                update.setParentId(newParentId);
                update.setLevel(newParentId == 0 ? 1 :
                        categoryService.getById(newParentId).getLevel() + 1);
            }
            update.setSort(newSort);
            update.setUpdateTime(new Date());
            categoryService.updateById(update);

            // 5. 如果修改了父分类，更新子分类level
            if (newParentId != null && !newParentId.equals(category.getParentId())) {
                updateChildrenLevel(categoryId);
            }

            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR(e.getMessage());
        }
    }

    /**
     * 检查是否移动到自己的子分类下
     */
    private boolean isDescendant(Long parentId, Long categoryId) {
        if (parentId == null || parentId == 0) {
            return false;
        }

        Category parent = categoryService.getById(parentId);
        while (parent != null) {
            if (parent.getId().equals(categoryId)) {
                return true;
            }
            parent = categoryService.getById(parent.getParentId());
        }
        return false;
    }

    /**
     * 更新子分类层级
     */
    private void updateChildrenLevel(Long parentId) {
        List<Category> children = categoryService.list(
                new QueryWrapper<Category>()
                        .eq("parent_id", parentId)
                        .eq("is_deleted", 0));

        Category parent = categoryService.getById(parentId);
        int newLevel = parent.getLevel() + 1;

        for (Category child : children) {
            Category update = new Category();
            update.setId(child.getId());
            update.setLevel(newLevel);
            update.setUpdateTime(new Date());
            categoryService.updateById(update);

            // 递归更新
            updateChildrenLevel(child.getId());
        }
    }

    /**
     * 计算排序值
     */
    private Integer calculateSortValue(Long parentId, String position, Long relativeId) {
        if ("append".equals(position)) {
            // 追加到末尾
            Integer maxSort = categoryService.getMaxSortByParentId(parentId);
            return maxSort != null ? maxSort + 10 :
                    (parentId == null || parentId == 0 ? 100 :
                            categoryService.getById(parentId).getSort() + 10);
        }

        // 获取参考分类
        Category relativeCat = categoryService.getById(relativeId);
        if (relativeCat == null) {
            throw new BusinessException("参考分类不存在");
        }

        if ("before".equals(position)) {
            // 插入到前面
            Integer prevSort = categoryService.getPrevSort(parentId, relativeCat.getSort());
            return prevSort != null ? (prevSort + relativeCat.getSort()) / 2 :
                    Math.max(1, relativeCat.getSort() - 10);
        } else {
            // 插入到后面
            Integer nextSort = categoryService.getNextSort(parentId, relativeCat.getSort());
            return nextSort != null ? (relativeCat.getSort() + nextSort) / 2 :
                    relativeCat.getSort() + 10;
        }
    }



    // 用户端查看分类以及品牌商品业务逻辑
    // 查看全部使用管理端查看全部分类即可

    // 二级分类查询
    @RequestMapping("findCategoryById1")
    public Result findCategoryById1() {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", 0)
                .eq("is_deleted", 0);
        List<Category> list = categoryService.list(wrapper);
        return Result.OK(list);
    }

    @RequestMapping("findCategoryById2")
    public Result findCategoryById2(@RequestParam Long parentId) {
        try {
            // 1. 验证一级分类是否存在
            Category parent = categoryService.getById(parentId);
            if (parent == null || parent.getIsDeleted() == 1 || parent.getLevel() != 1) {
                return Result.ERROR("一级分类不存在或无效");
            }

            // 2. 查询所有二级分类（使用条件构造器）
            QueryWrapper<Category> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", parentId)
                    .eq("level", 2)
                    .eq("is_deleted", 0)
                    .orderByAsc("sort");

            List<Category> secondLevelCategories = categoryService.list(wrapper);

            // 3. 为每个二级分类查询关联品牌
            List<Category> result = secondLevelCategories.stream().map(category -> {
                QueryWrapper<CategoryBrandRelation> brandWrapper = new QueryWrapper<>();
                brandWrapper.eq("category_id", category.getId());

                List<CategoryBrandRelation> relations = categoryBrandRelationService.list(brandWrapper);
                List<Long> brandIds = relations.stream()
                        .map(CategoryBrandRelation::getBrandId)
                        .collect(Collectors.toList());

                if (!brandIds.isEmpty()) {
                    List<Brand> brands = brandService.listByIds(brandIds).stream()
                            .filter(b -> b.getIsDeleted() == 0)
                            .collect(Collectors.toList());
                    category.setBrands(brands);
                }
                return category;
            }).collect(Collectors.toList());

            return Result.OK(result);
        } catch (Exception e) {
            return Result.ERROR("查询二级分类失败: " + e.getMessage());
        }
    }

    @RequestMapping("findCategoryById3")
    public Result findCategoryById3(@RequestParam Long parentId) {
        try {
            // 1. 验证二级分类是否存在
            Category parent = categoryService.getById(parentId);
            if (parent == null || parent.getIsDeleted() == 1 || parent.getLevel() != 2) {
                return Result.ERROR("二级分类不存在或无效");
            }

            // 2. 查询所有三级分类（使用条件构造器）
            QueryWrapper<Category> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", parentId)
                    .eq("level", 3)
                    .eq("is_deleted", 0)
                    .orderByAsc("sort");

            List<Category> thirdLevelCategories = categoryService.list(wrapper);

            // 3. 查询父分类（二级分类）关联的品牌
            QueryWrapper<CategoryBrandRelation> brandWrapper = new QueryWrapper<>();
            brandWrapper.eq("category_id", parentId);

            List<CategoryBrandRelation> relations = categoryBrandRelationService.list(brandWrapper);
            List<Long> brandIds = relations.stream()
                    .map(CategoryBrandRelation::getBrandId)
                    .collect(Collectors.toList());

            List<Brand> brands = new ArrayList<>();
            if (!brandIds.isEmpty()) {
                brands = brandService.listByIds(brandIds).stream()
                        .filter(b -> b.getIsDeleted() == 0)
                        .collect(Collectors.toList());
            }

            // 4. 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("categories", thirdLevelCategories);
            result.put("brands", brands);

            return Result.OK(result);
        } catch (Exception e) {
            return Result.ERROR("查询三级分类失败: " + e.getMessage());
        }
    }



    /**
     * 添加品牌接口
     * @param brandJson 品牌信息（json字符串，包含name、description、status、sort等）
     * @param logoFile 品牌logo文件
     * @param categoryIds 分类ID列表（可选，支持多级分类，前端传递如[1,2,3]，分别为一级、二级、三级分类ID）
     */
    @PostMapping(value = "/addBrand", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result addBrand(
            @RequestPart("brand") String brandJson,
            @RequestPart(value = "logo", required = false) MultipartFile logoFile,
            @RequestParam(value = "categoryIds", required = false) List<Long> categoryIds) {
        try {
            // 1. 解析品牌对象
            Brand brand = JSON.parseObject(brandJson, Brand.class);

            // 2. 处理logo上传
            if (logoFile != null && !logoFile.isEmpty()) {
                String logoUrl = minioUtil.upload(logoFile);
                brand.setLogo(logoUrl);
            }

            // 3. 排序逻辑：取当前最大sort+10，若无则为100
            Integer maxSort = brandService.lambdaQuery().select(Brand::getSort).orderByDesc(Brand::getSort).last("limit 1").oneOpt().map(Brand::getSort).orElse(100);
            brand.setSort(maxSort + 10);

            // 4. 其他字段
            brand.setCreateTime(new Date());
            brand.setUpdateTime(new Date());
            brand.setIsDeleted(0);

            // 5. 保存品牌
            brandService.save(brand);

            // 6. 处理品牌与分类的关联
            if (categoryIds != null && !categoryIds.isEmpty()) {
                for (Long categoryId : categoryIds) {
                    CategoryBrandRelation relation = new CategoryBrandRelation();
                    relation.setBrandId(brand.getId());
                    relation.setCategoryId(categoryId);
                    relation.setSort(brand.getSort());
                    relation.setCreateTime(new Date());
                    categoryBrandRelationService.save(relation);
                }
            }

            return Result.OK();
        } catch (Exception e) {
            return Result.ERROR("添加品牌失败: " + e.getMessage());
        }
    }
    /**
     * 查询品牌下的商品列表
     * @param brandId 品牌ID
     * @param categoryId 分类ID（可选）
     * @return 商品列表
     */
    @GetMapping("/findByBrand")
    public Result findByBrand(@RequestParam Long brandId, @RequestParam(required = false) Long categoryId) {
        try {
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("brand_id", brandId);
            if (categoryId != null) {
                queryWrapper.eq("category_id", categoryId);
            }
            queryWrapper.eq("deleted", 0); // 只查询未删除的商品
            queryWrapper.orderByDesc("create_time"); // 按创建时间降序排列

            List<Product> productList = productService.list(queryWrapper);
            return Result.OK(productList);
        } catch (Exception e) {
            return Result.ERROR("查询品牌下的商品失败: " + e.getMessage());
        }
    }
    /**
     * 灵活查询商品接口
     * @param brandId 品牌ID（可选）
     * @param categoryId 分类ID（可选，三级分类ID）
     * @return 商品列表
     */
    @GetMapping("/findProducts")
    public Result findProducts(
            @RequestParam(required = false) Long brandId,
            @RequestParam(required = false) Long categoryId) {

        try {
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();

            // 品牌ID条件
            if (brandId != null) {
                queryWrapper.eq("brand_id", brandId);
            }

            // 分类ID条件（三级分类）
            if (categoryId != null) {
                // 先验证是否为三级分类
                Category category = categoryService.getById(categoryId);
                if (category == null || category.getIsDeleted() == 1 || category.getLevel() != 3) {
                    return Result.ERROR("分类ID无效或不是三级分类");
                }
                queryWrapper.eq("category_id", categoryId);
            }

            queryWrapper.eq("deleted", 0) // 只查询未删除的商品
                    .orderByDesc("create_time"); // 按创建时间降序排列

            List<Product> productList = productService.list(queryWrapper);
            return Result.OK(productList);
        } catch (Exception e) {
            return Result.ERROR("查询商品失败: " + e.getMessage());
        }
    }

    @GetMapping("findProductById")
    public Result findProductById(int productId){
        Product byId = productService.getById(productId);
        Brand byId1 = brandService.getById(byId.getBrandId());
        byId.setBrand(byId1);
        Category byId2 = categoryService.getById(byId.getCategoryId());
        byId.setCategory(byId2);
        return Result.OK(byId);
    }
}
